<?php

namespace App\Models;

use Illuminate\Notifications\Notifiable;
use Illuminate\Auth\Authenticatable;
use Illuminate\Auth\MustVerifyEmail;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Foundation\Auth\Access\Authorizable;

use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
use Tymon\JWTAuth\Contracts\JWTSubject;

class User extends Model implements
    AuthenticatableContract,
    AuthorizableContract,
    CanResetPasswordContract,
    JWTSubject
{
    use Notifiable, Authenticatable, Authorizable, CanResetPassword, MustVerifyEmail;

    protected $fillable = [
        'name', 'email', 'password', 'phone', 'weixin_openid', 'weixin_unionid', 'weapp_openid', 'weixin_session_key', 'avatar', 'weapp_data',
    ];

    protected $hidden = [
        'password', 'remember_token',
    ];

    protected $casts = [
        'email_verified_at' => 'datetime',
        'weapp_data'        => 'json',
    ];


    /**
     * 关联模型
     */
    public function addresses()
    {
        return $this->hasMany(UserAddress::class);
    }

    public function replies()
    {
        return $this->hasMany(ArticleReply::class);
    }

    public function orders()
    {
        return $this->hasMany(Order::class);
    }


    /*
     * 修改器
     */
    public function setPasswordAttribute($value)
    {
        // 如果值的长度等于 60，即认为是已经做过加密的情况
        if (strlen($value) != 60) {

            // 不等于 60，做密码加密处理
            $value = bcrypt($value);
        }

        $this->attributes['password'] = $value;
    }


    /**
     * 访问器
     */
    public function getPointsRankAttribute()
    {
        return $this->newQuery()->where('points', '>', $this->points)->count() + 1;
    }

    public function getContactPhoneAttribute()
    {
        return $this->phone ?? data_get($this->addresses()->OrderByUseTime()->first(), 'contact_phone', '');
    }


    /**
     * jwt
     */
    public function getJWTIdentifier()
    {
        return $this->getKey();
    }

    public function getJWTCustomClaims()
    {
        return [];
    }

    /**
     * 积分操作
     */
    public function decreasePoints($points)
    {
        if ($points < 0) {
            // throw new InternalException('金额不可小于0');
        }else{
            return $this->newQuery()->where('id', $this->id)->where('points', '>=', $points)->decrement('points', $points);
        }
    }

    public function addPoints($points)
    {
        if ($points < 0) {
            // throw new InternalException('金额不可小于0');
        }else{
            $this->increment('points', $points);
        }
    }
}
